package test.netease.version3.chapter3.lesson_3_2_1;

/**
 * @author zhangrui
 * @date 2020-06-03 21:18
 * @since 1.0
 */
public class ClassLoaderView {
    public static void main(String[] args) {

        //通过ClassLoader可以获取到系统类加载器
        System.out.println(ClassLoader.getSystemClassLoader());
        System.out.println(ClassLoader.getSystemClassLoader().getParent());
        System.out.println(ClassLoader.getSystemClassLoader().getParent().getParent());

        ClassLoader classLoader = ClassLoaderView.class.getClassLoader();
        try {
            System.out.println("核心类库加载器 " +
                    classLoader.loadClass("java.lang.String").getClassLoader());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        try {
            System.out.println("拓展类库加载器 " +classLoader.loadClass("com.sun.nio.zipfs.ZipCoder").getClassLoader());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        System.out.println("应用程序库加载器 " + classLoader);

        System.out.println("应用程序库加载器的父类 " + classLoader.getParent());

        System.out.println("应用程序库加载器的父类的父类 " + classLoader.getParent().getParent());

        /**
         * 双亲委派机制：首先让父加载器去加载，父加载器加载不了，才自己加载
         *
         * public Class<?> loadClass(String name) throws ClassNotFoundException {
         *     return loadClass(name, false);
         * }
         *
         * protected synchronized Class<?> loadClass(String name, boolean resolve)
         *         throws ClassNotFoundException {
         *
         *     // 首先判断该类型是否已经被加载
         *     Class c = findLoadedClass(name);
         *     if (c == null) {
         *         //如果没有被加载，就委托给父类加载或者委派给启动类加载器加载
         *         try {
         *             if (parent != null) {
         *                 //如果存在父类加载器，就委派给父类加载器加载
         *                 c = parent.loadClass(name, false);
         *             } else {
         *                 //如果不存在父类加载器，就检查是否是由启动类加载器加载的类，
         *                 //通过调用本地方法native findBootstrapClass0(String name)
         *                 c = findBootstrapClass0(name);
         *             }
         *         } catch (ClassNotFoundException e) {
         *             // 如果父类加载器和启动类加载器都不能完成加载任务，才调用自身的加载功能
         *             c = findClass(name);
         *         }
         *     }
         *     if (resolve) {
         *         resolveClass(c);
         *     }
         *     return c;
         * }
         */
    }
}
